package com.lmxdawn.api.dnf.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.lmxdawn.api.admin.dao.auth.AuthAdminDao;
import com.lmxdawn.api.admin.entity.GoldCoin;
import com.lmxdawn.api.admin.entity.auth.AuthAdmin;
import com.lmxdawn.api.admin.service.IGoldCoinService;
import com.lmxdawn.api.common.api.Constants;
import com.lmxdawn.api.dnf.util.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx")
@Slf4j
public class WxAccessController {


    private final AuthAdminDao authAdminDao;
    @Resource
    IGoldCoinService goldCoinService;

    public WxAccessController(AuthAdminDao authAdminDao) {
        this.authAdminDao = authAdminDao;
    }

    @GetMapping("/index")
    public String configAccess(String signature,String timestamp,String nonce,String echostr) {
        log.info("接入微信公众号验证：===>【{}】【{}】【{}】【{}】", signature, timestamp, nonce, echostr);
        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        String token = "ACDE_ZH521314_aawbfsfhssjbvhd";
        String[] arr = {timestamp, nonce, token};
        Arrays.sort(arr);
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder sb = new StringBuilder();
        for (String temp : arr) {
            sb.append(temp);
        }
        // 2.1这里利用了hutool的加密工具类
        String sha1 = SecureUtil.sha1(sb.toString());
        // 3. 加密后的字符串与signature对比，如果相同则该请求来源于微信，原样返回echostr
        if (sha1.equals(signature)) {
            return echostr;
        }
        // 接入失败
        return null;
    }


    /**
     * 实现你问我答
     * @param request
     * @return
     */
    @PostMapping("/index")
    public String replyMessage(HttpServletRequest request){
        Map<String,String> map = MessageUtil.xmlToMap(request);
        log.info("接收到微信消息：===>【{}】", map);
        String toUserName = map.get("ToUserName");
        String fromUserName = map.get("FromUserName");
        String msgType = map.get("MsgType");
        String content = map.get("Content");
        String message = null;
        if (Constants.MessageType.MESSAGE_TEXT.equals(msgType)){
            //回复文本信息触发的消息
            message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT, "人工服务点击跳转网页会话，待开发");

        }else if (Constants.MessageType.MESSAGE_EVENT.equals(msgType)){
            //关注时触发的消息
            String event = map.get("Event");
            String eventKey = map.get("EventKey");

            if (Constants.MessageType.MESSAGE_SUBSCRIBE.equals(event)){
                message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,"欢迎关注老搬游戏交易平台\n" +
                        "买卖点击下方菜单进入平台\n" +
                        "营业时间：全天24小时营业\n" +
                        "\n" +
                        "\n" +
                        "防骗提醒：任何人以“兼职、刷单、返现、退款、保证金”等名义让您进行下单、引导您操作、或为他人进行代买游戏币，均为骗子！！！\n" +
                        "本平台是为大家提供游戏服务，非游戏交易被人引导付款或代付款都是被骗！！！");
                switch (eventKey) {
                    case "sale":
                        message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,
                                "-------出售比例-------\n" +
                                        DateUtil.now() +"\n" +
                                        "特价商城不定时更新额度\n" +
                                        "回收金币我们给包手续费\n" +
                                        "单笔出满500元优惠0.5比例\n" +
                                        "单笔出满3000元优惠1比例\n" +
                                        this.queryRate(3));
                        break;
                    case "buy":
                        message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,
                                "--------购买比例-------\n" +
                                        DateUtil.now() +"\n" +
                                        "特价商城不定时更新额度\n" +
                                        "单次购买500元优惠0.5比例\n" +
                                        "单次购买5000元优惠1比例\n" +
                                        this.queryRate(1)
                        );
                        break;
                    case "bxy":
                        message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,
                                "买卖辟邪玉请加微信：13258087111 \n （注意： 只买卖超出拍卖行价值的辟邪玉）"
                        );
                        break;
                    case "ts":
                        message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,
                                "投诉客服问题反馈请加微信：13258087111"
                        );
                        break;
                    case "fk":
                        message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,
                                "遇到BUG问题反馈或投诉客服问题反馈请加微信:13258087111"
                        );
                        break;

                }
            }else if (Constants.MessageType.MESSAGE_SCAN.equals(event)){
                log.info("===============================>SCAN=>{}", eventKey);
                if (eventKey.startsWith("bind")){
                    String userId = eventKey.replaceFirst("bind-", "");
                    this.bindUser(userId, fromUserName);
                    message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT, "绑定成功");
                }
            }else if (Constants.MessageType.CLICK.equals(event)){
                log.info("===============================>CLICK=>{}", eventKey);
                switch (eventKey) {
                    case "sale":
                        message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,
                                "-------出售比例-------\n" +
                                         DateUtil.now() +"\n" +
                                        "特价商城不定时更新额度\n" +
                                        "回收金币我们给包手续费\n" +
                                        "单笔出满500元优惠0.5比例\n" +
                                        "单笔出满3000元优惠1比例\n" +
                                        this.queryRate(3));
                        break;
                    case "buy":
                        message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,
                                "--------购买比例-------\n" +
                                        DateUtil.now() +"\n" +
                                        "特价商城不定时更新额度\n" +
                                        "单次购买500元优惠0.5比例\n" +
                                        "单次购买5000元优惠1比例\n" +
                                        this.queryRate(1)
                                        );
                        break;
                    case "bxy":
                        message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,
                                "购买辟邪玉请加微信：13258087111 \n （注意： 只买卖超出拍卖行价值的辟邪玉）"
                        );
                        break;
                    case "ts":
                        message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,
                                "投诉客服问题反馈请加微信：13258087111"
                        );
                        break;
                    case "fk":
                        message = MessageUtil.initText(toUserName,fromUserName, Constants.MessageType.MESSAGE_TEXT,
                                "遇到BUG问题反馈或投诉客服问题反馈请加微信:13258087111"
                        );
                        break;

                }
            }

        }
        return message;
    }


    private String queryRate(int type){
        List<GoldCoin> list = this.goldCoinService.lambdaQuery()
                .eq(GoldCoin::getType, type)
                .orderByAsc(GoldCoin::getGameServer)
                .list();
        StringBuilder str = new StringBuilder();
        for (GoldCoin item : list) {
            str.append(item.getGameServer());
            str.append(":");
            str.append(item.getGameServer().length() == 3 ? "  ": item.getGameServer().length() == 4 ? " ": "    ");
            str.append("1元=");
            str.append(item.getPrice());
            str.append("万\n");
        }
        return str.toString();
    }
    private void bindUser(String userId, String fromUserName) {
        AuthAdmin authAdmin = new AuthAdmin();
        authAdmin.setId(userId);
        authAdmin.setOpenId(fromUserName);
        authAdminDao.updateAuthAdmin(authAdmin);
    }

    public static void main(String[] args) {
        System.out.println(StringUtils.rightPad("跨1:", 6, " ")+"11");;
        System.out.println(StringUtils.rightPad("跨7/8:", 6, " ")+"11");
        System.out.println(StringUtils.rightPad("跨3B:", 6, " ")+"11");;
    }

}
